/** confirm.js */
var util = require('../../utils/util.js');
var pay = require('../../utils/pay.js');
var calc = require('../../utils/calc.js');
var cartapi = require('../../component/service/cartapi.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
  	orderId:'',
    type:'',
  	hidden:false,
    allAddress:[],
  	addresses:[],
    order:{},
    selectIndex:0,
    viewMore:true,
    coupon:{},
    payAmount:0,
    cantchange:false //是否生成订单，true为是，不得再改变地址以及优惠券
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let type = '';
    let orderId = typeof(options.orderId) == "undefined"?'':options.orderId;
    if(typeof(options.type)!="undefined"&&options.type=="custom"){
      type = 'custom';
    }   
    this.setData({
      platUser:getApp().globalData.platUser,
      orderId: orderId,
      type:type
    }) 
    cartapi.orderToConfirm(orderId,function(res){
      that.setData({
        order:res,
        hidden: true,
        payAmount:res.payableAmount
      })
      that.addresses();
    })

    //this.getData();
  },
  //过期~
  getData: function () {
  	var that = this;
    wx.request({
      //url: getApp().globalData.host + 'webapp/orders/detail.html',
      url: getApp().globalData.host + 'order/orderToConfirm',
      data: { orderId: that.data.orderId},
      header: getApp().globalData.header,
      method:'POST',
      success: function (res) {
        var tempOrder = res.data.order;
        tempOrder.orderSkus = res.data.skuMaps;
        tempOrder.createTime = util.formatTimeStamp(tempOrder.createTime);
        tempOrder.payTime = util.formatTimeStamp(tempOrder.payTime);
        tempOrder.deliveryTime = util.formatTimeStamp(tempOrder.deliveryTime);
        tempOrder.receivingTime = util.formatTimeStamp(tempOrder.receivingTime);
        if(typeof(tempOrder.orderSkus)!='undefined'&&tempOrder.orderSkus.length>0){
          for(let j = 0;j<tempOrder.orderSkus.length;j++){
            tempOrder.orderSkus[j].imgUrl = util.imageUrl(tempOrder.orderSkus[j].imgUrl);
          }
        }
        that.setData({
          order: tempOrder,
          hidden: true,
          payAmount:tempOrder.payableAmount
        });
        that.addresses();
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  addresses:function(){
    this.setData({
      addresses: [],
      viewMore:true
    });
  	var that = this;
  	wx.request({
      url: getApp().globalData.host + 'address/all.html',
      header: getApp().globalData.header,
      method:'POST',
      success: function (res) { 
      	var addresses = that.data.addresses;
        var defaultAddress = [];
        if (res.data == '' || res.data == null || res.data == undefined ||res.data.length==0) {
          return;
        }
        for (var i = 0; i < res.data.length; i++) {
          if(res.data[i].isDefault){
            res.data[i].selected = true;
            that.data.selectIndex = i;
            defaultAddress.push(res.data[i]);
          }
          addresses.push(res.data[i]);
        }
        that.setData({
          allAddress:addresses,
          addresses: defaultAddress,
          selectIndex: that.data.selectIndex
        });
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  //设置为默认地址
  defaultAddress:function(e){
    var that = this;
    var addressId = e.currentTarget.dataset.addressid;
    wx.request({
      url: getApp().globalData.host + 'address/setDefault.html',
      data: { id: addressId},
      method:'POST',
      header: getApp().globalData.header,
      success: function (res) {
        if(res.data.errorCode==0){
          wx.showToast({
            title: "设置成功",
            duration: 2000
          })
          that.addresses();
        }else{
          wx.showToast({
            title: "设置失败",
            duration: 2000
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  //修改收货地址
  modifyAddress:function(e){
    var addressId = e.currentTarget.dataset.addressid;
    wx.navigateTo({
      url: '../address/address?addressId=' + addressId,
    })
  },
  //删除收货地址
  delAddress:function(e){
    var that = this;
    var addressId = e.currentTarget.dataset.addressid;
    wx.showModal({
      title: '提示',
      content: '确认要删除该地址吗？',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: getApp().globalData.host + 'address/setDisabled.html',
            data: { id: addressId},
            method:'POST',
            header: getApp().globalData.header,
            success: function (res) {
              if(res.data.errorCode==0){
                wx.showToast({
                  title: "删除成功",
                })
                that.addresses();
              }else{
                wx.showToast({
                  title: "删除失败",
                })
              }
            },
            fail: function (res) { },
            complete: function (res) { }
          })
        }
      }
    })
  },
  //选择收货地址
  selectAddress:function(e){
    if(this.data.cantchange){
      wx.showModal({
        title: '提示',
        content:'当前订单已锁定，不得再修改地址。（若需修改，返回上一步重新确认订单）',
        showCancel:false
      })
      return;
    }
    var index = e.currentTarget.dataset.index;
    if(!this.data.addresses[index].selected){
      for(var i = 0;i<this.data.addresses.length;i++){
        if(this.data.addresses[i].selected){
          this.data.addresses[i].selected = false;
          break;
        }
      }
      this.data.addresses[index].selected = true;
      this.data.selectIndex = index;
    }
    this.setData({
      addresses:this.data.addresses,
      selectIndex:this.data.selectIndex
    })
  },
  //选择优惠券
  chooseCoupon:function(){
    if(this.data.cantchange){
      wx.showModal({
        title: '提示',
        content:'当前订单已锁定，不得再修改优惠方式。（若需修改，返回上一步重新确认订单）',
        showCancel:false
      })
      return;
    }
    let itemId = '';
    if(typeof(this.data.coupon.itemId)!='undefined')
      itemId = this.data.coupon.itemId;
    wx.navigateTo({
      url: '../coupon/coupon?orderId=' + this.data.orderId + '&itemId=' + itemId,
    })
  },
  //不使用优惠券
  nonuseCoupon:function(){
    this.setData({
      coupon:{},
      payAmount:this.data.order.payableAmount
    })
  },
  //使用优惠券
  useCoupon:function(coupon){
    if(typeof(coupon)=='undefined') return;
    let payAmount = calc.sub(this.data.order.payableAmount,coupon.denomination);
    this.setData({
      coupon:coupon,
      payAmount:payAmount
    })
  },
  //去付款
  doPay:function(){
    if(typeof(this.data.addresses[this.data.selectIndex])=='undefined'){
      wx.showModal({
        title: '提示',
        content:'请选择收货地址。',
        showCancel:false
      })
      return;
    }else{
      pay.toReducePay(this.data.order,this.data.addresses[this.data.selectIndex].addressId,this.data.coupon.itemId,this.data.payAmount);
      this.setData({
        cantchange:true
      })
    }
  },
  viewMore:function(){
    this.data.addresses = this.data.allAddress;
    this.setData({
      addresses:this.data.addresses,
      viewMore:false
    })
  }

})